<template>
    <el-container>
        <el-main>
            <div v-if="articles && articles.length">
                <el-card v-for="article in articles" :key="article._id" class="article-card">
                    <h2>{{ article.title }}</h2>
                    <p>{{ article.preview }}</p>
                    <el-button text @click="vuewDetail(article._id)">阅读更多</el-button>
                </el-card>
            </div>
            <div v-else class="no-data">No Data</div>
        </el-main>
    </el-container>
</template>

<script setup lang="ts">
import axios from '../axios'
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../store/auth'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
interface Article {
    _id: string,
    title: string,
    preview: string,
    content: string
}

const router = useRouter()
const authStore = useAuthStore()
const articles = ref<Article[]>([])

const fetchArticles = async () => {
    try {
        const res = await axios.get<Article[]>('/articles')
        articles.value = res.data
    } catch (error) {
        console.log('fetchArticles failed to load articles:', error)
    }
}

const vuewDetail = (id: string) => {
    if (!authStore.isAuthenticated) {
        ElMessage.error("请先登录再查看")
        return;
    }
    router.push({
        name: 'NewsDetails',
        params: { id }
    })

}

onMounted(fetchArticles)
</script>

<style scoped>
.article-card {
    margin: 20px 0;
}

.no-data {
    text-align: center;
    font-size: 1.2em;
    color: #999;
}
</style>